Return to doc.sitecore.com

Valid for Sitecore 5.2, 5.3
Populating a lookup field with the field values rather than item names

Consider the following problem. A user wants to refer to the Country items from your lookup field, but the lookup field must be populated with the field values rather than item names. 

If you specify a source field of your lookup field as /content/countries, you will get this field populated with the item names.

The instructions below show how to populate a lookup field with the field values rather than item names.

Assume that the country items are based on the Country template that defines a single field named ISO:

1.  Creating a Custom Lookup Field

Below is the full source code of the custom lookup field implemented in our example. Instructions on creating a custom field in Sitecore can be found here:

http://sdn.sitecore.net/Articles/API/Creating%20a%20Composite%20Custom%20Field/Adding%20a%20Custom%20Field%20to%20Sitecore%20Client.html

using System;
using System.Text;

using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Shell.Applications.ContentEditor;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.HtmlControls.Data;

namespace Sitecore.Shell.Applications.ContentEditor
{
  
public class CustomLookup : Lookup
   {
      
protected override void OnLoad(EventArgs args)
      {
        
if (!Sitecore.Context.ClientPage.IsEvent)
         {
            Item contextItem
= Sitecore.Context.ContentDatabase.Items[this.ItemID];

            
foreach(TemplateFieldItem tfItem in contextItem.Template.OwnFields)
            {
              
if(tfItem.Source == this.Source)
               {
                  FieldName
= tfItem.InnerItem.Fields["Field Name"].Value;
               }
            }
         }
        
base.OnLoad(args);
      }
   }
}

Here we override the OnLoad method with the code that sets the FieldName property to the value of the field.

The following logic is applied here: we iterate thorough the template’s fields of the context Item and compare the Source property of each field with the Source property of the field for which the control is called. If the sources match, the FieldName property of the CustomLookup class (this name is used in our example only) is set to the value of the template field (ISO in our case).

2.  Implementing a Custom Lookup Field

As a result, the lookup field will be populated with the values of the ISO field instead of the country names.